function [bci Train]=bciRetrainClassifier(bci,labelIdx,epochLabel,doTrain)
% [bci Train]=bciRetrainClassifier(bci,labelIdx,epochLabel,doTrain)
% creates train data adding new epochs (labelIdx is index to global MEMepoch)
% epochLabel are the corresponding labels, doTrain is optional (default:
% true) if false, only train data will be created

global MEMepoch;
global GLOBALtrainSet;

if nargin<4,
    doTrain=true;
end

% create new train data set
nOldTr = size(GLOBALtrainSet.dat,1);
nNewTr = length(labelIdx);
Train.label = [ GLOBALtrainSet.label; epochLabel];
epochIdxList = [1:nOldTr, 1:nNewTr];
selector = [ones(1,nOldTr),2*ones(1,nNewTr)];
goodEpoch=1:length(Train.label);
% bootstap new train set
if bci.param.bootstrapSize>0,
    bootstrapIdx = getBootstrappedTrainset(Train.label,bci.param.bootstrapSize);
    goodEpoch=[goodEpoch, goodEpoch(bootstrapIdx)];
end
% balance new train set
if bci.param.balanceTrainSet,
    label_bin = getBalancedTrainset(Train.label(goodEpoch),bci.param.maxTrainSamp,'leading');
    goodEpoch(~label_bin)=[];
%     tmp=find(label_bin)';
%     disp(tmp([1,end]));
end
Train.label = Train.label(goodEpoch);
selector = selector(goodEpoch);
Train.dat = zeros( length(goodEpoch),size(GLOBALtrainSet.dat,2));
Train.dat(selector==1,:)=GLOBALtrainSet.dat( epochIdxList(goodEpoch(selector==1)),:);
% add new trials
remainingTrials = epochIdxList(goodEpoch(selector==2));
tr=sum(selector==1)+1;
for trC=remainingTrials,
    Train.dat(tr,:) = bciTransformData(MEMepoch(:,:,labelIdx(trC)),bci,1);
        tr=tr+1;
end
% train classifier
if doTrain,
    bci=bciTrainClassifier(bci,Train);
end
% figure;imagesc([Train.dat(Train.label==2,:);Train.dat(Train.label==3,:)])
